package com.demo.stock.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 项目启动加载lua脚本
 *
 * @author admin
 */
@Scope(value = "singleton")
@Service(value = "luaScriptInit")
public class InitLuaScript {
    private static final Logger LOGGER = LoggerFactory.getLogger(InitLuaScript.class);
    private static List<String> luaScriptList = new ArrayList<>();
    static {
        luaScriptList.add("deductionStock.lua");
        luaScriptList.add("deductionStockRollback.lua");
    }
    /**
     * lua脚本集合
     */
    private ConcurrentHashMap<String, String> luaScript = new ConcurrentHashMap<>();
    /**
     * lua
     */
    private ConcurrentHashMap<String, String> luaShaCode = new ConcurrentHashMap<>();

    /**
     * 加载lua脚本
     */
    @PostConstruct
    public void loadLuaScript() {
        for (String luaScriptName : luaScriptList) {
            InputStream is = null;
            BufferedReader br = null;
            try {
                is = this.getClass().getResourceAsStream("/lua/" + luaScriptName);
                br = new BufferedReader(new InputStreamReader(is));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                is.close();
                br.close();
                String name = luaScriptName.substring(0, luaScriptName.lastIndexOf(".")).toUpperCase();
                luaScript.put(name, stringBuilder.toString());
                LOGGER.info("loadLuaScript load {} script success!", name);

            } catch (Exception e) {
                LOGGER.error("loadLuaScript error.", e);
            }
        }
    }

    public String getLuaScript(String name) {
        return luaScript.get(name.toUpperCase());
    }

    public void setLuaShaCode(String name, String content) {
        luaShaCode.put(name, content);
    }

    public String getLuaShaCode(String name) {
        return luaShaCode.get(name.toUpperCase());
    }
}

